//
//  LKComposePictureView.swift
//  LKWeibo
//
//  Created by like on 16/8/17.
//  Copyright © 2016年 like. All rights reserved.
//

import UIKit

// cell 可重用标示符
private let LKComposePictureViewCellId = "LKComposePictureViewCellId"

class LKComposePictureView: UICollectionView {

    //定义闭包 01
    var closure:(() -> ())?
    
    // 保存image 的数组
    var imageList: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    // MARK: - 供外界调用的方法
    func addImages(image: UIImage){
        self.hidden = false
        // 添加到数组中
        imageList.append(image)
        // 刷新UI
        reloadData()
    }
    
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        dataSource = self
        delegate = self
        self.hidden = true
        self.registerClass(LKComposePictureViewCell.self, forCellWithReuseIdentifier: LKComposePictureViewCellId)
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // cell间距
        let cellMargin: CGFloat = 5
        // cell 宽高
        let cellWH: CGFloat = (SCREENW - 20 - 2*cellMargin)/3
        // 设置itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直和水平间距
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
  
    }
}

//collectionview 代理
extension LKComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        let count = imageList.count
        //如果数组为0 9 数组长度不变
        if count == 0 || count == 9 {
            return imageList.count
        }
        
        return count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LKComposePictureViewCellId, forIndexPath: indexPath) as! LKComposePictureViewCell
        
        //cell.backgroundColor = RandomColor()

        
        if indexPath.item == imageList.count {
            
            cell.image = nil
            
        }else{
            
            cell.image = imageList[indexPath.item]
            
            //02 04
            cell.colesure = {[weak self]()->() in
             self?.imageList.removeAtIndex(indexPath.item)
                if self?.imageList.count == 0 {
                    // 隐藏当前控件
                    self?.hidden = true
                }
                // 刷新UI
                self?.reloadData()
                
            }
            
        }
        
        return cell
    }
    
    //选中cell后 一直是高亮状态 不回去， 就实现这个方法，
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //点击的是最后一张的时候
        if indexPath.item == imageList.count {

            //弹出控制器  03执行闭包
            closure?()
        }
    }
    
}


class LKComposePictureViewCell: UICollectionViewCell {
    
    //定义闭包
    var colesure:(()->())?
    //定义个image  供外界调用赋值
    var image: UIImage?{
        didSet{
            // 加号图片
            if image == nil {
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.hidden = true
            }else {
                bgImageView.image = image
                // 解决cell 复用问题
                bgImageView.highlightedImage = nil
                deleteButton.hidden = false
            }
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //删除按钮响应的事件
    func btnClick(){
        colesure?()   // 闭包 03
//        printLog("点击了")
    }
    
    private func setupUI(){
        backgroundColor = RandomColor()
        // 添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteButton)
        // 添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) in
            make.top.trailing.equalTo(contentView)
        }
    }
    
    private lazy var bgImageView:UIImageView = UIImageView()
    private lazy var deleteButton:UIButton = {
        let but = UIButton()
        but.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        but.addTarget(self, action: #selector(LKComposePictureViewCell.btnClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        return but
    }()
}
